package com.lzw.blog.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzw.blog.admin.mapper.*;
import com.lzw.blog.admin.model.params.PageCount;
import com.lzw.blog.admin.model.params.PageParam;
import com.lzw.blog.admin.pojo.*;
import com.lzw.blog.admin.vo.ArticleVo;
import com.lzw.blog.admin.vo.PageResult;
import com.lzw.blog.admin.vo.Result;

import org.apache.commons.lang3.StringUtils;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagService tagService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Autowired
    private ArticleBodyMapper articleBodyMapper;
    public Result listArticle(PageParam pageParam) {
        /**
         * 要的数据，管理台 表的所有的字段 Permission
         * 分页查询
         */
        Page<Article> page = new Page<>(pageParam.getCurrentPage(), pageParam.getPageSize());

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pageParam.getQueryString())) {
            queryWrapper.like(Article::getTitle, pageParam.getQueryString());
        }
        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);

        PageResult<ArticleVo> pageResult = new PageResult<>();
        pageResult.setList(copyList(articlePage.getRecords(), true, true, true));
        pageResult.setTotal(articlePage.getTotal());
        return Result.success(pageResult);
    }

    public Result delete(Long id) {
        // 删除对应评论
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Comment::getArticleId, id);
        int c = commentMapper.delete(lambdaQueryWrapper);

        // 删除对应标签
        LambdaQueryWrapper<ArticleTag> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(ArticleTag::getArticleId, id);
        int d = articleTagMapper.delete(lambdaQueryWrapper1);

        // 删除对应内容
        LambdaQueryWrapper<ArticleBody> articleBodyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleBodyLambdaQueryWrapper.eq(ArticleBody::getArticleId, id);
        articleBodyMapper.delete(articleBodyLambdaQueryWrapper);

        articleMapper.deleteById(id);
        return Result.success(null);
    }

    /**
     * 生成界面交互 ActicleVo
     * @param records
     * @param isTag
     * @param isAuthor
     * @param category
     * @return
     */
    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor, boolean category) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isTag, isAuthor, category));
        }
        return articleVoList;
    }

    public ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean category) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);
        Long createDate = article.getCreateDate();
        long milliseconds = createDate * 1000; // 将秒级时间戳转换为毫秒级时间戳

        DateTime dateTime = new DateTime(milliseconds);
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
        String formattedDateTime = dateTime.toString(formatter);
        articleVo.setCreateDate(formattedDateTime);
        //并不是所有文章的都有标签和作者
        if (isTag) {
            Long articleId = article.getId();
            List<Tag> tags = tagService.findTagsByArticleId(articleId);
            List<String> tagsName = new ArrayList<>();
            for (Tag t : tags) {
                tagsName.add(t.getTagName());
            }
            articleVo.setTagsName(tagsName);
        }

        if (isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(userService.findUserById(authorId).getNickname());
        }
        //是否存在分类
        if (category) {
            Long categoryId = article.getCategoryId();
            articleVo.setCategoryName(categoryService.findcategoryByid(categoryId).getCategoryName());
        }
        return articleVo;
    }

    /**
     * 返回文章总量
     * @return
     */
    public Result getNums() {
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        PageCount pageCount = new PageCount();
        pageCount.setCount(articleMapper.selectCount(lambdaQueryWrapper));

        return Result.success(pageCount);
    }

    /**
     * 返回最新文章
     * @param limit
     * @return
     */
    public Result newArticles(int limit) {
        //最新文章
        //查询条件
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.last("limit "+limit);
        //select id,title from ms_article group by create_date limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);
        List<ArticleVo> articleVos = copyList(articles, true, true, true);
        return Result.success(articleVos);
    }
}
